namespace Brjnk.CoordinateSystem2D
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;

    /// <summary>
    /// </summary>
    public class TemplateCache
    {
        private static List<Tuple<DataTemplate, Freezable>> loadedTemplates = new List<Tuple<DataTemplate, Freezable>>();

        public static DependencyObject GetContent(DataTemplate template)
        {
            var item = loadedTemplates.FirstOrDefault(i => object.ReferenceEquals(i.Item1, template));
            if (item != null)
            {
                return item.Item2.Clone();
            }
            else
            {
                var content = template.LoadContent();
                var freezable = content as Freezable;
                if (freezable != null)
                {
                    loadedTemplates.Add(new Tuple<DataTemplate, Freezable>(template, freezable));
                    PurgeLoadedTemplates();
                    return freezable.Clone();
                }
                else return content;
            }
        }

        private static void PurgeLoadedTemplates()
        {
            if (loadedTemplates.Count > 5) loadedTemplates.RemoveAt(loadedTemplates.Count - 1);
        }
    }
}